import json
import os
import time
import cv2
import base64
import requests


def has_pic(stu_id=''):
    if stu_id == '':
        return False
    else:
        if os.path.isfile('pics/' + stu_id + '.jpg'):
            return True
        else:
            return False


def image_to_base64(image_np):
    image = cv2.imencode('.jpg', image_np)[1]
    image_code = str(base64.b64encode(image))[2:-1]

    return image_code


def get_token():
    client_id = '7sjrEzFrVX3R0FsyL84qXTT0'
    client_secret = 'tvMhGyzp2AlBm9q0YUbZRxOxjB4xMTY3'

    # client_id 为官网获取的AK， client_secret 为官网获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    response = requests.get(host)
    if response:
        data = response.json()

        data['expires_in'] += int(time.time())
        with open('token.json', 'w', encoding='utf-8') as fp:
            fp.write(json.dumps(data, indent=2, ensure_ascii=False))

        return data['access_token']
    else:
        return False


def get_access_token():
    with open('token.json', 'r', encoding='utf8') as fp:
        json_data = json.load(fp)

    # 若超时重新获取
    if int(time.time()) > (json_data['expires_in'] - 10):
        access_token = get_token()
        if not access_token:
            return False
        else:
            return access_token

    # 返回 access_token
    return json_data['access_token']


def compare(img_a_base64, stu_id):
    img_b = cv2.imread('pics/' + stu_id + '.jpg')
    img_b_base64 = image_to_base64(img_b)

    # 发送请求
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"

    params = "[{\"image\": \"" + img_a_base64 + "\", \"image_type\": \"BASE64\", \"face_type\": \"LIVE\"},{\"image\": \"" + img_b_base64 + "\", \"image_type\": \"BASE64\", \"face_type\": \"LIVE\"}]"
    access_token = get_access_token()
    request_url = request_url + "?access_token=" + access_token
    headers = {'Content-Type': 'application/json'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        json_data = response.json()
        if json_data['error_code'] == 0:
            return json_data['result']['score'] > 80
        else:
            return False
    else:
        return False
